<template>
  <CommonPage title="商品档案" content-row>
    <div class="w-72 mr-4 border border-solid border-gray-200 flex flex-col overflow-hidden">
      <div class="p-4 bg-gray-100 font-semibold"> 供应商档案 </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          class="table-pg-px0"
          :columns="supplierColumns"
          row-key="id"
          :data-source="supplierData"
          :pagination="supplierPagination"
          :loading="supplierLoading"
          :custom-row="customRow"
          :row-selection="{
            type: 'radio',
            selectedRowKeys,
            onChange,
          }"
        ></SlTable>
      </div>
    </div>
    <div class="flex-1 flex flex-col overflow-hidden">
      <div class="mb-4">
        <a-button type="primary" :disabled="selectedRowKeys.length === 0" @click="showCreateModal">
          新增商品档案
        </a-button>
      </div>
      <div class="flex-1 overflow-hidden">
        <SlTable
          class="table-pg-px0"
          :columns="columns"
          row-key="id"
          :data-source="tableData"
          :pagination="pagination"
          :loading="tableLoading"
        >
          <template #bodyCell="{ column, record }">
            <div v-if="column.key === 'oper'">
              <div>
                <a @click="showUpdateModal(record)">编辑</a>
                <a class="ml-2 text-red-400" @click="handleDelete(record)">删除</a>
              </div>
              <div>
                <a @click="showMpDetail(record)">小程序详情</a>
              </div>
            </div>
            <div v-else-if="column.dataIndex === 'thumbnail'">
              <a-image :fallback="DEFAULT_IMG_BASE64_STR" :src="record.thumbnail" :width="48" />
            </div>
          </template>
        </SlTable>
      </div>
    </div>
    <CURDDialog
      ref="CURDModalIns"
      id-key="id"
      create-title="新增商品档案"
      update-title="编辑商品档案"
      delete-message="确认删除该商品档案吗？"
      :show-options="showOptions"
      :model="model"
      :model-form-setting="modelFormSetting"
      :table-data="tableData"
      :curd="curd"
      :reload-table="reloadTable"
      :get-detail="getDetail"
      :columns="columns"
      @open="handleOpen"
      @before-ok="beforeOk"
    />
    <a-modal
      v-model:visible="mpModalVisible"
      wrap-class-name="mp-modal"
      :width="450"
      title="小程序详情"
      :mask-closable="false"
      :body-style="{ padding: '8px' }"
      @ok="handleMpOk"
    >
      <EditorFormItem :value="mpContent" @change="mpContentChange" />
    </a-modal>
  </CommonPage>
</template>
<script setup lang="ts">
import { onMounted, ref, watch } from "vue";
import { useCURD } from "/@/hooks/useCURD";
import { TableProps } from "ant-design-vue";
import { getDictOptions } from "/@/api/main/system";
import { DictTypeCode } from "/@/api/main/system/models";
import {
  CURDAction,
  FormItemComponentType,
  FormItemData,
  ShowCURDModalOptions,
  CURDDialogExpose,
  CURDModalEvent,
} from "/@/components/CURDDialog/models";
import { ProductFileItem, CompanyType, SupplierItem } from "/@/api/main/pis/models";
import { Api, updateIntroduction } from "/@/api/main/pis";
import { DEFAULT_IMG_BASE64_STR } from "/@/utils/file";
import { enumToOptions, getLabelByValueFromEnum, priceRender } from "/@/utils/common";
/**
 * 供应商
 */
const supplierColumns = ref<TableProps<SupplierItem>["columns"]>([
  {
    title: "名称",
    dataIndex: "name",
  },
]);
const selectedRowKeys = ref<number[]>([]);
function onChange(keys: number[]) {
  selectedRowKeys.value = keys;
}
function customRow(record: SupplierItem) {
  return {
    onclick: () => {
      selectedRowKeys.value = [record.id];
    },
  };
}
const {
  pagination: supplierPagination,
  tableData: supplierData,
  tableLoading: supplierLoading,
  reloadTable: reloadSupplier,
} = useCURD<SupplierItem>({
  getPageUrl: Api.supplierPage,
  loadOnMounted: false,
  simplePagination: true,
});
onMounted(async () => {
  await reloadSupplier();
  if (supplierData.value.length > 0) {
    selectedRowKeys.value = [supplierData.value[0].id];
  }
});
watch(selectedRowKeys, (keys) => {
  reloadTable({ model: { supplierId: keys.length > 0 ? keys[0] : "" } });
});
/**
 * 商品表格
 */
const columns = ref<TableProps<ProductFileItem>["columns"]>([
  {
    title: "商品图片",
    dataIndex: "thumbnail",
  },
  {
    title: "编码",
    dataIndex: "productCode",
  },
  {
    title: "条码",
    dataIndex: "barCode",
  },
  {
    title: "品名",
    dataIndex: "name",
  },
  {
    title: "供应商",
    dataIndex: "supplierName",
  },
  {
    title: "商品类别",
    dataIndex: "productType",
  },
  {
    title: "商城分类",
    dataIndex: "mallClass",
  },
  {
    title: "产地",
    dataIndex: "productArea",
  },
  {
    title: "规格",
    dataIndex: "specifications",
  },
  {
    title: "计量单位",
    dataIndex: "measurementUnit",
  },
  {
    title: "克重",
    dataIndex: "weight",
  },
  {
    title: "有效期标准",
    dataIndex: "validityCriteria",
  },
  {
    title: "进货价",
    dataIndex: "purchasePrice",
    customRender: priceRender,
  },
  {
    title: "售价",
    dataIndex: "price",
    customRender: priceRender,
  },
  {
    title: "批发价",
    dataIndex: "wholesalePrice",
    customRender: priceRender,
  },
  {
    title: "税率",
    dataIndex: "taxRate",
  },
  {
    title: "保存方式",
    dataIndex: "saveAs",
  },
  {
    title: "积分比率",
    dataIndex: "pointRedemptionRatio",
  },
  {
    title: "状态",
    dataIndex: "status",
  },
  {
    title: "操作",
    key: "oper",
    width: 100,
    fixed: "right",
  },
]);

const { pagination, tableData, tableLoading, curd, reloadTable } = useCURD<ProductFileItem>({
  getPageUrl: Api.productFilePage,
  cudUrl: Api.productFiles,
  loadOnMounted: false,
});
/**
 * 供应商窗
 */
const CURDModalIns = ref<CURDDialogExpose>();
const showOptions = ref<ShowCURDModalOptions>();
const model = ref<Partial<ProductFileItem>>({
  productTypeId: null,
  barCode: "",
  name: "",
  mallClassId: null,
  supplierName: "",
  thumbnail: "",
  validityCriteria: "",
  productArea: "",
  specifications: "",
  measurementUnit: null,
  weight: "",
  purchasePrice: null,
  price: null,
  wholesalePrice: null,
  pointRedemptionRatio: null,
  taxRate: "",
  saveAs: "",
});
const modelFormSetting = ref<FormItemData[]>([
  {
    key: "productTypeId",
    type: FormItemComponentType.TREESELECT,
    async getData(e) {
      const data = await getDictOptions({ typeCode: DictTypeCode.productCategory });
      return data || [];
    },
    required: true,
    label: "商品类别",
  },
  {
    key: "barCode",
    required: true,
  },
  {
    key: "name",
    required: true,
  },
  {
    key: "mallClassId",
    label: "商城分类",
    type: FormItemComponentType.TREESELECT,
    async getData(e) {
      const data = await getDictOptions({ typeCode: DictTypeCode.mallClass });
      return data || [];
    },
    required: true,
  },
  {
    key: "thumbnail",
    label: "商品图片",
    type: FormItemComponentType.IMGUPLOAD,
    required: true,
  },
  {
    key: "validityCriteria",
    type: FormItemComponentType.NUMBER,
    labelDes: "单位：天",
    required: true,
    props: {
      min: 1,
    },
  },
  {
    key: "productArea",
  },
  {
    key: "specifications",
  },
  {
    key: "measurementUnit",
    type: FormItemComponentType.SELECT,
    props: {
      options: [],
    },
    async getData() {
      const data = await getDictOptions({ typeCode: DictTypeCode.measurementUnit });
      return data || [];
    },
  },
  {
    key: "weight",
  },
  {
    key: "purchasePrice",
    type: FormItemComponentType.NUMBER,
  },
  {
    key: "price",
    type: FormItemComponentType.NUMBER,
  },
  {
    key: "wholesalePrice",
    type: FormItemComponentType.NUMBER,
  },
  {
    key: "pointRedemptionRatio",
    type: FormItemComponentType.NUMBER,
  },
  {
    key: "taxRate",
  },
  {
    key: "saveAs",
  },
  {
    key: "supplierName",
    props: {
      disabled: true,
    },
  },
]);
function handleOpen() {
  // model.value.supplierId = selectedRowKeys.value[0];
  const target = supplierData.value.find((el) => el.id === selectedRowKeys.value[0]);
  if (target) {
    model.value.supplierName = target.name;
  }
}
function beforeOk({ model }: CURDModalEvent<Partial<ProductFileItem>>) {
  if (model) {
    delete model.supplierName;
    model.supplierId = selectedRowKeys.value[0];
  }
}
function showCreateModal() {
  showOptions.value = { action: CURDAction.CREATE };
}
function showUpdateModal(record) {
  showOptions.value = { action: CURDAction.UPDATE, record };
}
function handleDelete(record) {
  showOptions.value = { action: CURDAction.DELETE, ids: [record.id] };
}
async function getDetail(record) {
  return {};
}
/**
 * mpModalVisible
 */
const mpModalVisible = ref(false);
const mpContent = ref("");
let curProductForMp: ProductFileItem | null = null;
function showMpDetail(record: ProductFileItem) {
  curProductForMp = record;
  mpContent.value = record.introduction || "";
  mpModalVisible.value = true;
}
function mpContentChange(val) {
  mpContent.value = val;
}
async function handleMpOk() {
  if (curProductForMp) {
    const re = await updateIntroduction(curProductForMp.id, mpContent.value);
    if (re === undefined) {
      mpModalVisible.value = false;
      reloadTable();
    }
  }
}
</script>
<style lang="less">
.mp-modal {
  .ant-modal {
    top: 0;
  }
}
</style>
